<template>
  <div class="app-container">
    <div v-if="lange" class="qrCodeContainer" style="width: 450px; height: 50px; display: none; width: 100%">
      <h1 class="title" style="width: 480px; margin-left: 45%; font-size: 17px">{{ $t(`Print.PurchaseInboundList`) }}</h1>
      <div style="width: 95%; margin: auto">
        <div style="display: flex; width: 100%; font-size: 13px; justify-content: space-between">
          <h2 style="font-size: 13px; font-size: 11px">{{ $t(`Print.Manufacturers`) }}:{{ slipNoList3[0]?.vendorName }}</h2>
          <h2 style="margin-left: 50px; font-size: 13px; font-size: 11px">{{ $t(`Print.ArrivalDate`) }}:{{ slipNoList3[0]?.sendDate }}</h2>
          <h2 style="margin-left: 50px; font-size: 13px; font-size: 11px">{{ $t(`Print.InboundOrderNumber`) }}:{{ slipNoList3[0]?.recNo }}</h2>
          <h2 style="margin-left: 50px; font-size: 13px; font-size: 11px">{{ $t(`Print.DeliveryNoteNumber`) }}:{{ slipNoList3[0]?.sendNo }}</h2>
          <h2 style="margin-left: 50px; font-size: 13px; font-size: 11px">{{ $t(`Print.DateOfPrinting`) }}:{{ formatCurrentDateTime(currentDate) }}</h2>
        </div>

        <div style="width: 100%">
          <table style="width: 100%; font-size: 13px">
            <thead>
              <tr>
                <th>{{ $t(`Print.Directives`) }}</th>
                <th>{{ $t(`Print.MaterialColorKey`) }}</th>
                <th>{{ $t(`Print.MaterialName`) }}</th>
                <th>{{ $t(`Print.Specification`) }}</th>
                <th>{{ $t(`Print.Unit`) }}</th>
                <th>{{ $t(`Print.Type`) }}</th>
                <th>{{ $t(`Print.TActualAmountReceivedype`) }}</th>
                <th>{{ $t(`Print.Remark`) }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(iten1, index) in slipNoList3" :key="index">
                <td>{{ iten1.purLot }}</td>

                <td>{{ iten1.mtlColor }}</td>
                <td>{{ iten1.mtlName }}</td>
                <td>{{ iten1.mtlSpec }}</td>
                <td>{{ iten1.mtlUnit }}</td>

                <td>{{ iten1.slipType }}</td>
                <td>{{ iten1.sendQty }}</td>

                <td>{{ iten1.remark }}</td>
                <!-- 更多的数据单元格 -->
              </tr>
              <!-- 更多的行 -->
            </tbody>
            <!-- 可选的 tfoot 部分 -->
          </table>

          <!-- <Table :tableHeader="tableHeader5" :tableData="slipNoList" /> -->
        </div>
        <h3 style="margin-left: 650px; font-size: 7px !important">{{ $t(`Print.TotalDispatch`) }}:{{ numberList.toFixed(2) }}</h3>
        <div style="padding: 0; margin: 0; font-size: 11px; line-height: normal; font-weight: normal; font-family: inherit; color: inherit">
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">{{ $t(`Print.Illustrate`) }}</h3>
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">
            {{ $t(`Print.WhenDeliveringYouMustBringTheDeliveryNoteToThePlaceToPrintTheWarehousingOrderTheGoodsArriveAtTheOrderIfYouDoNotBringTheOrderWillBeDelayedThankYouForYourCooperation`) }}
          </h3>
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">
            {{ $t(`Print.TheSupplyOrderMustContainInstructionSheetMaterialColorMaterialNameSpecificationQuantityUnitUnitPriceAmountIncludingTaxOrExclusiveDeliveryPeriod`) }}
          </h3>
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">{{ $t(`Print.AccordingToTheConfirmedSamplesAndTestResultsWeAreWillingToAcceptTheBuyersReturnOrDiscountWhenTheQualityIsPoor`) }}</h3>
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">
            {{ $t(`Print.PleaseDliverTheGoodsDuringWorkingHoursWillNotReceiveTheGoodsDuringTheOffdutyHoursIfThereAreSpecialCircumstancesPleaseContactThePurchasingDepartmentOfTheSupplyCenterTankYou`) }}
          </h3>
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">
            {{ $t(`Print.IfTheDeliveryIsDelayed005OfTheTotalOrderPriceIsUsedAsLiquidatedDamagesAndTheSupplierShallBearAllTheLossesCausedByTheDeliveryTimeAndPoorQuality`) }}
          </h3>
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">TEL:18296370303</h3>
        </div>

        <div style="display: flex; justify-content: space-between; width: 85%; font-size: 17px; width: 80%; margin: auto">
          <h2 style="font-size: 13px">{{ $t(`Print.Attn`) }}:</h2>
          <h2 style="font-size: 13px">{{ $t(`Print.Reviewers`) }}:</h2>
          <h2 style="font-size: 13px">{{ $t(`Print.Manufacturers`) }}:</h2>
          <h2 style="font-size: 13px">{{ $t(`Print.ReceiptInspector`) }}:</h2>
        </div>
      </div>
    </div>

    <div v-else class="qrCodeContainer" style="width: 450px; height: 50px; display: none; width: 100%">
      <h1 class="title" style="width: 480px; margin-left: 35%; font-size: 17px">PHIẾU NHẬP KHO -NGUYÊN LIỆU</h1>
      <h1 class="title" style="width: 480px; margin-left: 42%; font-size: 17px">{{ formattedDate }}</h1>
      <h1 class="title" style="width: 480px; margin-left: 38%; font-size: 17px">Số 编号: {{slipNoList3[0]?.recNo}}</h1>

      <h1 class="title" style="width: 480px; font-size: 17px">Họ và tên người giao:</h1>
      <h1 class="title" style="width: 480px; font-size: 17px">Theo Hợp Đồng gia công  số :</h1>
      <h1 class="title" style="width: 480px; font-size: 17px">Theo Tờ khai hải quan số:</h1>
      <h1 class="title" style="width: 480px; font-size: 17px">Nhập tại kho:</h1>

      <div style="width: 95%; margin: auto">
       

        <div style="width: 100%">
          <table style="width: 100%; font-size: 13px">
            <thead>
              <tr>
                <th>STT</th>
                <th>Mã NL</th>
                <th>Tên, nhãn hiệu, quy cách hàng hóa</th>
                <th>Mã số thu mua</th>
                <th>Đơn vị tính</th>
                <th>Số lượng</th>
                <th>Ghi Chú</th>
              </tr>
            </thead>
            <tbody>
              <tr >
                <td></td>
                <tr style="display: grid; grid-template-columns: 1fr 1fr 1fr;">
                    <th style="border-right: 1px solid;">Mã HQ</th>
                    <th style="border-right: 1px solid;">Mã kho</th>
                    <th>物料编码</th>
                  </tr>
                <td></td>
                <td></td>
                <td></td>
                <tr style="display: grid; grid-template-columns: 1fr 1fr;">
                    <th style="border-right: 1px solid;">Mã HQ</th>
                    <th style="border-right: 1px solid;">Mã kho</th>
                  </tr>
                <!-- <td>Thực nhập</td>
                <td>Theo chứng từ</td> -->
                <!-- 更多的数据单元格 -->
              </tr>
              <tr v-for="(iten1, index) in slipNoList3" :key="index">

                <td>{{ index + 1 }}</td>

                <td>
  <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; width: 100%;">
    <div style="border-right: 1px solid; padding: 5px;">{{ iten1.mtlNoHg }}</div>
    <div style="border-right: 1px solid; padding: 5px;">{{ iten1.mtlNoHg }}</div>
    <div style="padding: 5px;">{{ iten1.mtlNo }}</div>
  </div>
</td>
                  
                <td>{{ iten1.mtlName }} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ iten1.mtlNameEng
 }}</td>

                <td>{{ iten1.purNo }}</td>
                <td>{{ iten1.mtlUnit}}</td>

                  <td>
  <div style="display: grid; grid-template-columns: 1fr 1fr ; width: 100%;">
    <div style="border-right: 1px solid; padding: 5px;">{{ iten1.sendQty }}</div>
    <div style="padding: 5px;">{{ iten1.sendQty }}</div>
  </div>
</td>

                <td>{{ iten1.remark }}</td>
                <!-- 更多的数据单元格 -->
              </tr>
              <!-- 更多的行 -->
            </tbody>
            <!-- 可选的 tfoot 部分 -->
          </table>

          <!-- <Table :tableHeader="tableHeader5" :tableData="slipNoList" /> -->
        </div>
        <!-- <h3 style="margin-left: 650px; font-size: 21px !important">{{ $t(`Print.TotalDispatch`) }}:{{ numberList.toFixed(2) }}</h3> -->
        <h3 style="margin-left: 850px; font-size: 13px !important">{{ formattedDate }}</h3>

        <div style="display: flex; justify-content: space-between; width: 85%; font-size: 17px; width: 80%; margin: auto">
          <h2 style="font-size: 13px">Người lập phiếu:</h2>
          <h2 style="font-size: 13px">Người nhận hàng :</h2>
          <h2 style="font-size: 13px">Thủ kho:</h2>
          <h2 style="font-size: 13px">
            <h1 style="font-size: 13px">Kế toán trưởng:</h1>
          </h2>
        </div>
      </div>
    </div>

    <Find :OriginalFilter="{ static: true }" :formList="formList1" @Launchform="Launchform" @findClicked="findClicked" />
    <Find :OriginalFilter="{ static: true }" :searchImg="false" :formList="formList" @Launchform="Launchform1" />

    <el-card style="margin-top: 7px" shadow="always" :body-style="{ padding: '20px' }">
      <div>
        <h1>{{ $t(`Print.OrderUnreceivedInquiry`) }}</h1>
        <div>
          <Table
            @currentRow1="clicktogetdata3"
            class="Active"
            @selectList="selectListT"
            :selection="true"
            style="margin-bottom: 10px"
            :summaryData="summaryData"
            summary
            :tableHeader="tableHeader"
            :tableData="TheQueryDataStoreIsNotReceived.dtos"
            :TableHeight="110"
            :outTableHeight="225"
            @currentRow="clicktogetdata"
            :isLoading="isLoading"
          />
          <span class="mr10">{{ $t(`Print.MaterialName`) }}</span>
          <el-input class="mr55" placeholder="" size="small" clearable @change="" style="width: 331px" v-model="inputValue"> </el-input>
          <PageModule style="margin-top: 5px" :PageData="{ total }" @pageChange="handleSizeChange" @pageSizeChange="handleCurrentChange" />
        </div>
      </div>
      <div>
        <h1>{{ $t(`Print.OrderReceivedInquiry`) }}</h1>
        <Table
          @currentRow="clicktogetdata5"
          style="margin-bottom: 10px"
          @selectList="selectList"
          :selection="true"
          :summaryData="summaryData1"
          summary
          :tableHeader="tableHeader1"
          :tableData="TheQueryDataStoreIsNotReceivedAll.dtos"
          :TableHeight="50"
          :outTableHeight="160"
          @inputChange="confirmChange"
          :getTableList="QueryUncollectedMethodToObtainDataAll"
          :isLoading="isLoading1"
        />
        <PageModule :PageData="{ total: totalT }" @pageChange="handleSizeChangeT" @pageSizeChange="handleCurrentChangeT" />
      </div>
    </el-card>

    <!-- 分类定义 -->
    <el-drawer v-model="drawer1" title="I am the title" :with-header="false">
      <h1 style="font-size: 16px; margin-bottom: 40px">{{ $t(`Print.ClassificationDefinitions`) }}</h1>
      <div style="display: flex; justify-content: space-between; width: 70%">
        <div>
          <h1>{{ $t(`Print.ClassificationDetails`) }}</h1>
          <Table
            @selectList="selectListTc"
            :selection="true"
            :tableData="classificationCode.head"
            :tableHeader="tableHeader4"
            :TableHeight="100"
            :isLoading="isLoading6"
          />
        </div>
        <div style="display: flex; flex-direction: column; margin-top: 120px; align-items: center">
          <el-button type="primary" size="default" @click="selectionSort" style="width: 80px; height: 25px">{{ $t(`Print.SelectAClassification`) }}</el-button>
          <el-button type="primary" size="default" @click="selectionSort1" style="margin-top: 100px; width: 80px; height: 25px; margin-right: 10px">
            &lt;&lt; {{ $t(`Print.RestoreTheClassification`) }}
          </el-button>
        </div>

        <div>
          <Table
            style="margin-top: 18px"
            :tableData="classificationCode.user"
            :tableHeader="tableHeader5"
            :TableHeight="100"
            @currentRow="clicktogetdata1"
            :isLoading="isLoading6"
          />
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import LoginWork from '@/utils/LoginWork'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'TemporaryReceiptStorage'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { ref, onMounted, watch } from 'vue'
import {
  VendorData1,
  QueryNotReceived,
  QueryReceived,
  StorageBatchProcessing,
  AddedATemporaryJob,
  VendorData,
  MaterialSuspense,
  MaterialAdditionAndDeletion,
  ModifyDelete,
  PutIntoStorage
} from '@/api/WarehouseDepartment/FactoryStorage/TemporaryReceiptStorage'
import type {
  ExampleQueryUnreceivedParameters,
  QueryNotReceivedInterface,
  MaterialSuspenseInterface,
  ModifyDeleteInterface
} from '@/api/WarehouseDepartment/FactoryStorage/TemporaryReceiptStorage'
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus'
// 双击填充数量
const clicktogetdata3 = (row: any, blum: string) => {
  if (blum === 'OrderQuantity') {
    row.OrderQuantity = row.unSendQty
    row.sendDate = formatCurrentDate(currentDate.value)
  }
}
const date = new Date();
const formattedDate = date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0');
const RedrawTheLabelMethodsParms = ref('')
const slipNoList3 = ref<any>([])

// 实收
const numberList = ref(0)

const clicktogetdata5 = (row: any) => {
  slipNoList3.value = TheQueryDataStoreIsNotReceivedAll.value.dtos.filter((item: any) => row.recNo === item.recNo)
  // 假设 numberList 是一个变量，想要保存总和
  numberList.value = slipNoList3.value.reduce((accumulator: any, current: any) => {
    return accumulator + (current.sendQty || 0) // Ensure sendQty is treated correctly
  }, 0)
}

// 日期
const formatCurrentDateTime = (date?: Date) => {
  const year = date!.getFullYear()
  const month = String(date!.getMonth() + 1).padStart(2, '0') // 使用padStart确保月份是两位数
  const day = String(date!.getDate()).padStart(2, '0') // 使用padStart确保日期是两位数
  const hours = String(date!.getHours()).padStart(2, '0') // 小时
  const minutes = String(date!.getMinutes()).padStart(2, '0') // 分钟
  const seconds = String(date!.getSeconds()).padStart(2, '0') // 秒

  // 返回格式化的日期时间字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const formList1 = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入订购单号',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入指令',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入型体',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料名称',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料颜色',
    inputValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '分类',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'date',
    dateLabel: '订购日期',
    dateValue: ''
  },
  {
    type: 'date',
    dateLabel: '送货日期',
    dateValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '厂商',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'button',
    checkboxLabel: '查询未收'
  },
  {
    type: 'button',
    checkboxLabel: '查询全部未收'
  },
  {
    type: 'button',
    checkboxLabel: '查询已收'
  },
  {
    type: 'button',
    checkboxLabel: '查询全部已收'
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  },
  {
    type: 'button',
    checkboxLabel: '暂收入库'
  },
  {
    type: 'button',
    checkboxLabel: '分类定义'
  },
  {
    type: 'button',
    checkboxLabel: '入库批处理'
  },
  {
    type: 'input',
    inputPlaceholder: '请输入入库单号',
    inputValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '入库单(连打)'
  },
  {
    type: 'button',
    checkboxLabel: '转入仓库'
  },
  {
    type: 'button',
    checkboxLabel: '修改'
  }
])

const formList = ref([
  // {
  //   type: 'input',
  //   inputLabel: '待分配数量',
  //   inputValue: ''
  // },
  // {
  //   type: 'input',
  //   inputLabel: '—    已分配数量',
  //   inputValue: '',
  //   inputDisabled: true
  // },
  // {
  //   type: 'input',
  //   inputLabel: '未分配数量',
  //   inputValue: Number(),
  //   inputDisabled: true
  // },
  {
    type: 'input',
    inputPlaceholder: '请输入送货单号',
    inputValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '厂商',
    selectLabel: '',
    selectOptions: []
  }
])

// 数据存储
const TheQueryDataStoreIsNotReceived = ref<QueryNotReceivedInterface>({
  unsentSum: 0,
  dtos: [],
  qtySum: 0
})

const warehouseEntryNumber = ref('')

const WarehousingMethod = async () => {
  const result = await PutIntoStorage(warehouseEntryNumber.value)
  if (result.code === 200) {
    formList1.value[17].inputValue = ''
    JMessage.success(result.message)
    QueryUncollectedMethodToObtainDataAll()
  } else {
    QueryUncollectedMethodToObtainDataAll()
    JMessage.error(result.message)
  }
}

const MaterialAdditionAndDeletionParameters = ref<any>([])

const clicktogetdata1 = (row: any) => {
  const { typeNo, typeName } = row || {}
  let valueOfList = {
    typeNo,
    typeName
  }
  MaterialAdditionAndDeletionParameters.value.push(valueOfList)
  JMessage.warning('已添加' + MaterialAdditionAndDeletionParameters.value.length + '条')
}

const _vendorName = ref<string>('')

const ModifyDeleteParameter = ref([])

const ModifyDeleteMethod = async () => {
  const result = await ModifyDelete(ModifyDeleteParameter.value)
  if (result.code === 200) {
    QueryUncollectedMethodToObtainDataAll()
    QueryUncollectedMethodToObtainData()
    JMessage.success(result.message)
  } else {
    JMessage.error(result.message)
  }
}

const handleClose3 = (_done?: () => void) => {
  ElMessageBox.confirm('确定要删除该数据吗')
    .then(() => {
      ModifyDeleteMethod()
    })
    .catch(() => {})
}

const isLoading = ref(true)

const isLoading1 = ref(true)

const _stringSendNo = ref('')

const isLoading6 = ref(true)

const selectionSort1 = async () => {
  flag.value = 2
  const result = await MaterialAdditionAndDeletion(MaterialAdditionAndDeletionParameters.value, flag.value)
  if (result.code === 200) {
    JMessage.success(result.message)
    MaterialAdditionAndDeletionParameters.value.length = 0
    MaterialsAreTemporarilyAcceptedForInput()
  } else {
    JMessage.success(result.message)
    MaterialAdditionAndDeletionParameters.value.length = 0
    MaterialsAreTemporarilyAcceptedForInput()
  }
}

const selectionSort = async () => {
  if (MaterialAdditionAndDeletionParameters.value.length === 0) {
    return JMessage.warning('请选择记录')
  }
  flag.value = 1
  const result = await MaterialAdditionAndDeletion(MaterialAdditionAndDeletionParameters.value, flag.value)
  if (result.code === 200) {
    JMessage.success(result.message)
    MaterialAdditionAndDeletionParameters.value.length = 0
    MaterialsAreTemporarilyAcceptedForInput()
  } else {
    JMessage.success(result.message)
    MaterialAdditionAndDeletionParameters.value.length = 0
    MaterialsAreTemporarilyAcceptedForInput()
  }
  MaterialsAreTemporarilyAcceptedForInput()
}

const flag = ref()

const selectListTc = (selectList: any) => {
  MaterialAdditionAndDeletionParameters.value = selectList.map((itme: any) => {
    return {
      typeNo: itme.typeNo,
      typeName: itme.typeName
    }
  })
}

const MaterialsAreTemporarilyAcceptedForInput = async () => {
  isLoading6.value = true
  const result = await MaterialSuspense()
  classificationCode.value.head = result.head
  classificationCode.value.user = result.user
  isLoading6.value = false
}

const classificationCode = ref<MaterialSuspenseInterface>({
  head: [],
  user: []
})

const tableHeader4 = ref([
  {
    label: '分类代码',
    prop: 'typeNo'
  },
  {
    label: '分类名称',
    prop: 'typeName'
  }
])

const tableHeader5 = ref([
  {
    label: '分类代码',
    prop: 'typeNo'
  },
  {
    label: '分类名称',
    prop: 'typeName'
  }
])

// 分类定义
const drawer1 = ref(false)

// 修改后点击确定按钮
const confirmChange = async (row: any) => {
  const result = await LoginWork.put<any, any>(
    `/pcFactorStockQuery/purSentRemark?primaryId=${row.primaryId}&sendDate=${row.sendDate}&sendNo=${row.sendNo}&remark=${row.remark}`
  )
  if (result.code === 200) {
    QueryUncollectedMethodToObtainDataAll()
    JMessage.success(result.message)
  } else {
    JMessage.error(result.message)
  }
}

const EvaluatesTheArrayReturnValue = (ArrayList: any) => {
  return ArrayList.map((item: any, index: any) => {
    return {
      optionKey: index,
      optionValue: item,
      optionLabel: item
    }
  })
}

const VendorDataShow = async () => {
  const result = await VendorData()
  const result1 = await VendorData1()
  let NewArray = []
  let NewArray1 = []
  let NewArray2 = []

  NewArray = result.mtlType.reduce((arr: any, item: any) => {
    if (item.typeName && item.typeNo) {
      // 只添加非空的 typeName 和 typeNo
      arr.push(item.typeNo + ' ' + item.typeName)
    }
    return arr
  }, [])
  NewArray1 = result.vendor.reduce((arr: any, item: any) => {
    if (item.vendorNo && item.vendorName) {
      // 只添加非空的 typeName 和 typeNo
      arr.push(item.vendorNo + ' ' + item.vendorName)
    }
    return arr
  }, [])

  NewArray2 = result1.list.reduce((arr: any, item: any) => {
    if (item.vendorNo && item.vendorName) {
      // 只添加非空的 typeName 和 typeNo
      arr.push(item.vendorNo + ' ' + item.vendorName)
    }
    return arr
  }, [])

  formList1.value[5].selectOptions = EvaluatesTheArrayReturnValue(NewArray)
  formList1.value[8].selectOptions = EvaluatesTheArrayReturnValue(NewArray1)
  formList.value[1].selectOptions = EvaluatesTheArrayReturnValue(NewArray2)
}

const currentDate = ref(new Date())

const formatCurrentDate = (date: any) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份加 1 并格式化为双位
  const day = String(date.getDate()).padStart(2, '0') // 日期格式化为双位
  return `${year}-${month}-${day}`
}

const _MultiplyAccumulate = ref(0)

const NumberList1 = ref<number[]>([])

// 转入仓库
watch(formList.value, (newInputValue, oldInputValue) => {
  // if (formList.value[3].inputValue !== '' && formList.value[0].inputValue !== '') {
  //   // 将对象属性按照索引排序
  //   const sortedKeys = Object.values(TheQueryDataStoreIsNotReceived.value.dtos);
  //   // 遍历排序后的属性值
  //   sortedKeys.forEach(key => {
  //     key.change = ''
  //     // 在这里处理每个项目
  //   });
  // }
  // if (Number(formList.value[0].inputValue) - Number(formList.value[1].inputValue) === 0 && NumberList1.value.length !== 0) {
  //   if (TheQueryDataStoreIsNotReceived.value.dtos.length !== 0) {
  //     // 将对象属性按照索引排序
  //     const sortedKeys = Object.values(TheQueryDataStoreIsNotReceived.value.dtos);
  //     if (!TableActive.value) {
  //       JMessage.warning('已分配完')
  //     }
  //     // 遍历排序后的属性值
  //     sortedKeys.forEach(key => {
  //       key.change = null as any
  //       // 在这里处理每个项目
  //     });
  //   }
  // }
})

const selectListT = (selectList: any) => {
  // if (selectList[selectList.length - 1] !== undefined) {
  //   _MultiplyAccumulate.value += Number(selectList[selectList.length - 1]?.unSendQty)
  //   NumberList1.value?.push(_MultiplyAccumulate.value)
  //   if (formList.value[0].inputValue === '') {
  //     return JMessage.warning('待分配数量不可为空')
  //   } else {
  //     if (selectList[selectList.length - 1].unSendQty >= (formList.value[0] as any).inputValue) {
  //       selectList[selectList.length - 1].OrderQuantity = Number(formList.value[0].inputValue) - Number(formList.value[1].inputValue)
  //       formList.value[1].inputValue = (formList.value[0] as any).inputValue
  //       formList.value[2].inputValue = (formList.value[0] as any).inputValue - (formList.value[1] as any).inputValue
  //     } else {
  //       if (selectList[selectList.length - 1]?.unSendQty < (formList.value[0] as any).inputValue) {
  //         selectList[selectList.length - 1].OrderQuantity = selectList[selectList.length - 1]?.unSendQty
  //         formList.value[1].inputValue = Number(formList.value[1].inputValue) + Number(selectList[selectList.length - 1]?.unSendQty) as number;
  //         formList.value[2].inputValue = (formList.value[0] as any).inputValue - (formList.value[1] as any).inputValue
  //         if (Number(formList.value[1].inputValue) > Number(formList.value[0].inputValue)) {
  //           formList.value[1].inputValue = formList.value[0].inputValue
  //           formList.value[2].inputValue = (formList.value[0] as any).inputValue - (formList.value[1] as any).inputValue
  //         }
  //         if (_MultiplyAccumulate.value > (formList.value[0] as any).inputValue) {
  //           selectList[selectList.length - 1].OrderQuantity = (formList.value[0] as any).inputValue - NumberList1.value[NumberList1.value.length - 2]
  //           formList.value[1].inputValue = (formList.value[0] as any).inputValue
  //           formList.value[2].inputValue = (formList.value[0] as any).inputValue - (formList.value[1] as any).inputValue
  //         }
  //       }
  //     }
  //   }
  //   selectList[selectList.length - 1].DeliveryDate = formatCurrentDate(currentDate.value);
  //   _newArrayAddedTemporary.value = selectList.map((item: any) => {
  //     return {
  //       purNo: item.purNo,
  //       slipType: item.slipType,
  //       purStyle: item.purStyle,
  //       purColor: item.purColor,
  //       ordQty: item.ordQty,
  //       mtlSpec: item.mtlSpec,
  //       mtlUnit: item.mtlUnit,
  //       qty: item.qty,
  //       overQty: item.overQty,
  //       minusQty: item.minusQty,
  //       unSendQty: item.unSendQty,
  //       mtlNo: item.mtlNo,
  //       reqNo: item.reqNo,
  //       companyId: item.companyId,
  //       purDate: item.purDate,
  //       purLot: item.purLot,
  //       mtlColor: item.mtlColor,
  //       mtlName: item.mtlName,
  //       sendQty: item.OrderQuantity,
  //       vendorName: item.vendorName,
  //     }
  //   })
  // }
}

const TableActive = ref(false)

const _newArrayAddedTemporary = ref<any>([])

const AddedATemporaryJobInterface = async () => {
  _newArrayAddedTemporary.value = TheQueryDataStoreIsNotReceived.value.dtos.filter((item: any) => item.OrderQuantity)
  _newArrayAddedTemporary.value = _newArrayAddedTemporary.value.map((item: any) => {
    item.sendQty = item.OrderQuantity
    item.slipType = item.purType
    item.hgId = item.hgId
    return item
  })
  const result = await AddedATemporaryJob(_newArrayAddedTemporary.value!, _vendorName.value as string, _stringSendNo.value as string)
  if (result.code !== 200) {
    JMessage.error(result.message)
    TableActive.value = true
  } else {
    TableActive.value = true
    JMessage.success(result.message)
    QueryUncollectedMethodToObtainData()
    QueryUncollectedMethodToObtainDataAll()
  }
}

const clicktogetdata = (row: any) => {
  const { mtlName } = row || {}
  inputValue.value = mtlName
}

const inputValue = ref('')

interface summaryDataType {
  index: number
  num: number | undefined
}

const summaryData = ref<summaryDataType[]>([
  {
    index: 12,
    num: 0
  },
  {
    index: 16,
    num: 0
  }
])

const summaryData1 = ref<summaryDataType[]>([
  {
    index: 12,
    num: 0
  }
])

const active = ref()

// 查询已收存储数据
const TheQueryDataStoreIsNotReceivedAll = ref<QueryNotReceivedInterface>({
  unsentSum: 0,
  dtos: [],
  qtySum: 0
})

const _OrderQueried = ref([])

const _StorageBatchProcessing = async () => {
  _OrderQueried.value.map((_item: any) => {})
  const result = await StorageBatchProcessing(_OrderQueried.value)
  if (result.code === 200) {
    JMessage.success('入库批处理成功')
    QueryUncollectedMethodToObtainDataAll()
    return
  } else {
    JMessage.error(result.message)
  }
}

const selectList = (selectedList: any) => {
  _OrderQueried.value = selectedList.map((item: any) => {
    const { purNo, purLot, sendQty, vendorName, sendNo, recNo, mtlColor, mtlName, slipType, mtlUnit, mtlSpec } = item || {}

    return {
      purNo,
      purLot,
      sendQty,
      vendorName,
      sendNo,
      recNo,
      mtlColor,
      mtlName,
      slipType,
      mtlUnit,
      mtlSpec
    }
  })
  ModifyDeleteParameter.value = selectedList.map((item: any) => {
    const { mtlColor, mtlName, purLot, purNo, recNo, sendNo, sendQty, slipType, vendorName } = item || {}

    return {
      mtlColor,
      mtlName,
      purLot,
      purNo,
      recNo,
      sendNo,
      sendQty,
      slipType,
      vendorName
    }
  })
  if (_OrderQueried.value.length !== 0) {
    warehouseEntryNumber.value = (_OrderQueried?.value as any)[_OrderQueried?.value?.length - 1].recNo || ''
    formList1.value[17].inputValue = warehouseEntryNumber.value
  }
}

// 查询已收
const QueryUncollectedMethodToObtainDataAll = async () => {
  isLoading1.value = true
  const result = await QueryReceived(QueryUncollectedMethodsToObtainDataParametersAll.value)
  if (result.data !== null) {
    let filteredArray = result.data.dtos.filter((item) => item !== null)
    TheQueryDataStoreIsNotReceivedAll.value.dtos = filteredArray.map((item: any) => {
      item.change = 'Y'
      item.disableConfirm = true
      return item
    })
    totalT.value = result.data.total!
    summaryData1.value[0].num = result.data.sendSum
  } else {
    TheQueryDataStoreIsNotReceivedAll.value.dtos = []
  }

  isLoading1.value = false
}

const QueryUncollectedMethodsToObtainDataParametersAll = ref<ExampleQueryUnreceivedParameters>({
  dateEnd: '',
  dateStart: '',
  mtlColor: '',
  mtlName: '',
  pageNum: 1,
  pageSize: 40,
  purLot: '',
  purNo: '',
  purStyle: '',
  typeNo: '',
  vendorName: '',
  allFlag: 0
})

const QueryUncollectedMethodsToObtainDataParameters = ref<ExampleQueryUnreceivedParameters>({
  dateEnd: '',
  dateStart: '',
  mtlColor: '',
  mtlName: '',
  pageNum: 1,
  pageSize: 40,
  purLot: '',
  purNo: '',
  purStyle: '',
  typeNo: '',
  vendorName: '',
  allFlag: 0
})

// 查询未收
const QueryUncollectedMethodToObtainData = async () => {
  isLoading.value = true
  const result = await QueryNotReceived(QueryUncollectedMethodsToObtainDataParameters.value)
  if (result === null) {
    TheQueryDataStoreIsNotReceived.value.dtos = []
    isLoading.value = false
    return
  }
  if (result.dtos) {
    TheQueryDataStoreIsNotReceived.value.dtos = result.dtos.map((item: any) => {
      item.change = 'Y'
      item.disableConfirm = true
      // item.unSendQty = Number(item.qty) + Number(item.overQty) - Number(item.sendQty)
      return item
    })
    // result.dtos.forEach((item: any) => {
    //   item.change = null
    // })
  }

  const firstMtlName = result.dtos?.[0]?.mtlName

  if (firstMtlName !== undefined) {
    inputValue.value = result.dtos[0]?.mtlName || ''
  }
  total.value = result.total!
  summaryData.value[0].num = result.qtySum
  summaryData.value[1].num = result.unsentSum
  isLoading.value = false
}

// 分页器
const total = ref(0)

const handleSizeChange = (val: number) => {
  QueryUncollectedMethodsToObtainDataParameters.value.pageNum = val
  QueryUncollectedMethodToObtainData()
}

const handleCurrentChange = (val: number) => {
  QueryUncollectedMethodsToObtainDataParameters.value.pageSize = val
  QueryUncollectedMethodToObtainData()
}

// 分页器
const totalT = ref(0)

const handleSizeChangeT = (val: number) => {
  QueryUncollectedMethodsToObtainDataParametersAll.value.pageNum = val
  QueryUncollectedMethodToObtainDataAll()
}

const handleCurrentChangeT = (val: number) => {
  QueryUncollectedMethodsToObtainDataParametersAll.value.pageSize = val
  QueryUncollectedMethodToObtainDataAll()
}

// 统一调用接口
const interAceFunct = () => {
  // 查询未收方法获取数据
  QueryUncollectedMethodToObtainData()

  // Find下拉框数据
  QueryUncollectedMethodToObtainDataAll()

  // 厂商数据
  VendorDataShow()
}

// 用户信息
const userInfo = ref()

onMounted(() => {
  interAceFunct()

  let userInf = sessionStorage.getItem('userInfo')

  userInfo.value = JSON.parse(userInf!)

  const lang = localStorage.getItem('language')
  if (lang === 'vi') {
    lange.value = false;
  } else {
    lange.value = true;
  }
})

// 表格数据
const tableHeader = ref([
  {
    label: '订购单号',
    prop: 'purNo',
    change: true
  },
  {
    label: '类型',
    prop: 'purType',
    change: true
  },
  {
    label: '厂商名称',
    prop: 'vendorName',
    change: true
  },
  {
    label: '指令',
    prop: 'purLot',
    change: true
  },
  {
    label: '型体',
    prop: 'purStyle',
    change: true
  },
  {
    label: '配色',
    prop: 'purColor',
    change: true
  },
  {
    label: '订单量',
    prop: 'ordQty',
    change: true
  },
  {
    label: '材料颜色',
    prop: 'mtlColor',
    change: true
  },
  {
    label: '材料名称',
    prop: 'mtlName',
    change: true
  },
  {
    label: '海关编码',
    prop: 'mtlNoHg',
    change: true
  },
  {
    label: '规格',
    prop: 'mtlSpec',
    change: true
  },
  {
    label: '单位',
    prop: 'mtlUnit',
    change: true
  },
  {
    label: '正单用量',
    prop: 'qty',
    change: true
  },
  {
    label: '预加量',
    prop: 'overQty',
    change: true
  },
  {
    label: '多购量',
    prop: 'minusQty',
    change: true
  },
  {
    label: '已收数量',
    prop: 'sendQty',
    change: true
  },
  {
    label: '未收数量',
    prop: 'unSendQty',
    change: true
  },
  {
    label: '正单数量',
    prop: 'OrderQuantity'
  },
  {
    label: '预加量',
    prop: 'overQty',
    change: true
  },
  {
    label: '多购量',
    prop: 'minusQty'
  },
  {
    label: '送货日期 ',
    prop: 'sendDate',
    type: 'dateSingle'
  },
  {
    label: '备注',
    prop: 'remark',
    change: true
  }
])

const tableHeader1 = ref([
  {
    label: '类型',
    prop: 'slipType',
    change: true
  },
  {
    label: '送货日期',
    prop: 'sendDate',
    type: 'dateSingle'
  },
  {
    label: '送货单号',
    prop: 'sendNo'
  },
  {
    label: '订购单号',
    prop: 'purNo',
    change: true
  },
  {
    label: '厂商名称',
    prop: 'vendorName',
    change: true
  },
  {
    label: '指令',
    prop: 'purLot',
    change: true
  },
  {
    label: '型体',
    prop: 'purStyle',
    change: true
  },
  {
    label: '材料颜色',
    prop: 'mtlColor',
    change: true
  },
  {
    label: '材料名称',
    prop: 'mtlName',
    change: true
  },
  {
    label: '规格',
    prop: 'mtlSpec',
    change: true
  },
  {
    label: '单位',
    prop: 'mtlUnit',
    change: true
  },
  {
    label: '暂收数量',
    prop: 'sendQty',
    change: true
  },
  {
    label: '备注',
    prop: 'remark'
  },
  {
    label: '入库单号',
    prop: 'recNo',
    change: true
  },
  {
    label: '海关编码',
    prop: 'mtlNoHg',
  }
])

const Launchform = (row: any) => {
  QueryUncollectedMethodsToObtainDataParameters.value.purNo = row[0].inputValue
  QueryUncollectedMethodsToObtainDataParameters.value.purLot = row[1].inputValue
  QueryUncollectedMethodsToObtainDataParameters.value.purStyle = row[2].inputValue
  QueryUncollectedMethodsToObtainDataParameters.value.mtlName = row[3].inputValue
  QueryUncollectedMethodsToObtainDataParameters.value.mtlColor = row[4].inputValue
  QueryUncollectedMethodsToObtainDataParameters.value.dateStart = row[6].dateValue[0]
  QueryUncollectedMethodsToObtainDataParameters.value.dateEnd = row[6].dateValue[1]
  QueryUncollectedMethodsToObtainDataParameters.value.typeNo = row[5].selectValue?.split(' ')[0]?.trim()
  QueryUncollectedMethodsToObtainDataParameters.value.vendorName = row[8].selectValue.split(' ')[1]

  // QueryUncollectedMethodsToObtainDataParametersAll.value.purNo = row[0].inputValue
  // QueryUncollectedMethodsToObtainDataParametersAll.value.purLot = row[1].inputValue
  // QueryUncollectedMethodsToObtainDataParametersAll.value.purStyle = row[2].inputValue
  // QueryUncollectedMethodsToObtainDataParametersAll.value.mtlName = row[3].inputValue
  // QueryUncollectedMethodsToObtainDataParametersAll.value.mtlColor = row[4].inputValue
  // QueryUncollectedMethodsToObtainDataParametersAll.value.dateStart = row[7].dateValue[0]
  // QueryUncollectedMethodsToObtainDataParametersAll.value.dateEnd = row[7].dateValue[1]
  // QueryUncollectedMethodsToObtainDataParametersAll.value.typeNo = row[5].selectValue?.split(' ')[0]?.trim()

  if (active.value === 0) {
    QueryUncollectedMethodToObtainData()
    return
  } else if (active.value === 1) {
    QueryUncollectedMethodToObtainDataAll()
    return
  }
  if (active.value === 2) {
    QueryUncollectedMethodToObtainDataAll()
    return
  }
  if (row[7].dateValue.length !== 0) {
    QueryUncollectedMethodToObtainDataAll()
    return
  }
  if (warehouseEntryNumber.value === '') {
    QueryUncollectedMethodToObtainData()
  }
}

const Launchform1 = (row: any) => {
  if (isNaN(row[0].inputValue)) {
    // formList.value[0].inputValue = 1;
  }
  _stringSendNo.value = row[0].inputValue
  _vendorName.value = row[1].selectValue?.split(' ')[0]?.trim()
}

const printQRCode = () => {
  const qrCodeContainer = document.querySelector<any>('.qrCodeContainer')
  if (qrCodeContainer) {
    // 临时显示 .qrCodeContainer 以获取其内容
    qrCodeContainer.style.display = 'block'

    const printWindow = window.open('', '_blank')
    printWindow!.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>打印指令领料作业</title>
          <link rel="stylesheet" type="text/css" href="print.css" media="print">
          <style>
            body, html {
              margin: 0;
              padding: 0;
            }
            @page {
              size: auto; 
              margin: 3mm;
            }
            @media print {
                /* 打印时的样式 */
             
                
                /* 其他打印样式 */
            }
            h2 {
                    margin-left: initial; /* 或者设置适合打印的左边距 */
                    page-break-inside: avoid; /* 避免在h2元素内部分页 */
                }
            h3{
              font-size:13px;
            }
               

            table, th, td {
                    border: 1px solid black; 
                    border-collapse: collapse; 
                    text-align: center;
                  }
                  th, td {
                    padding: 5px; /* 设置内边距 */
                    text-align: left; /* 设置文本对齐方式 */
                    text-align: center;
                    font-size:11px
                  }
                  .double-line {
                    border-top: 2px dashed red; 
                    border-bottom: 2px dashed red; 
                    text-align: center;
                  }
           
            /* 可以在这里添加更多自定义的打印样式 */
          </style>
        </head>
        <body>
    `)

    // 将 .qrCodeContainer 的内容复制到打印窗口的 body 中
    const cloneContainer = qrCodeContainer.cloneNode(true)
    printWindow!.document.body.appendChild(cloneContainer)

    printWindow!.document.write(`
        </body>
      </html>
    `)
    printWindow!.document.close()

    // 开始打印
    printWindow!.print()

    // 打印完成后，可以恢复 .qrCodeContainer 的原始显示状态
    qrCodeContainer.style.display = 'none'
  }
}

const lange = ref(false)

const findClicked = (find: any) => {
  if (find === '置空') {
    clearFormList1()
    QueryUncollectedMethodToObtainData()
    QueryUncollectedMethodToObtainDataAll()
  }
  if (find === '查询未收') {
    active.value = false
    QueryUncollectedMethodsToObtainDataParameters.value.allFlag = 0
    // clearFormList1()
    QueryUncollectedMethodToObtainData()
  }
  if (find === '查询全部未收') {
    active.value = 0
    QueryUncollectedMethodsToObtainDataParameters.value.allFlag = 1
    // clearFormList1()
    QueryUncollectedMethodToObtainData()
  }
  if (find === '查询已收') {
    active.value = 1
    QueryUncollectedMethodsToObtainDataParametersAll.value.allFlag = 0
    // clearFormList1()
    QueryUncollectedMethodToObtainDataAll()
  }
  if (find === '查询全部已收') {
    active.value = 2
    QueryUncollectedMethodsToObtainDataParametersAll.value.allFlag = 1
    // clearFormList1()
    QueryUncollectedMethodToObtainDataAll()
  }
  if (find === '入库批处理') {
    if (_OrderQueried.value.length === 0) {
      JMessage.warning('请选择需要入库批处理的数据')
      return
    }
    _StorageBatchProcessing()
  }
  if (find === '暂收入库') {
    if (_vendorName.value === '' || _stringSendNo.value === '') {
      return JMessage.warning('送货单号或厂商不可为空')
    }

    _MultiplyAccumulate.value = 0

    // clearFormList1()

    TableActive.value = true

    AddedATemporaryJobInterface()
  }
  if (find === '分类定义') {
    drawer1.value = true
    MaterialsAreTemporarilyAcceptedForInput()
  }
  if (find === '修改') {
    if (ModifyDeleteParameter.value.length === 0) {
      return JMessage.warning('请勾选需要删除的订购已收')
    }
    handleClose3()
  }
  if (find === '转入仓库') {
    if (warehouseEntryNumber.value === '') {
      return JMessage.warning('入库单号不可为空')
    }
    WarehousingMethod()
  }
  if (find === '入库单(连打)') {
    const lang = localStorage.getItem('language')
    if(lang === 'vi'){
      lange.value = false
    }else{
      lange.value = true
    }
    if (slipNoList3.value.length === 0) {
      JMessage.warning('请点击需要打印的数据')
    } else if (slipNoList3.value[0].recNo === null) {
      JMessage.warning('请选择有入库单号的进行打印')
    } else {
      printQRCode()
    }
  }
}

const clearFormList1 = () => {
  formList1.value.forEach((item) => {
    if (item.type === 'input') {
      item.inputValue = ''
    }
    if (item.type === 'select') {
      item.selectValue = ''
    }
    if (item.type === 'date') {
      item.dateValue = ''
    }
    // Add other conditions for different form item types
  })
  formList.value.forEach((item: any) => {
    if (item.type === 'input') {
      item.inputValue = ''
    }
    if (item.type === 'select') {
      item.selectValue = ''
    }
    if (item.type === 'date') {
      item.dateValue = ''
    }
    // Add other conditions for different form item types
  })
}
</script>

<style lang="less" scoped>
h1 {
  font-size: 16px;
}

.Active {
  :deep(.el-table__header) {
    .el-table__cell:first-child {
      .cell {
        display: none;
      }
    }
  }
}
</style>
